package core

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

var notePath string
var outPath string
var navList []string // 顶部导航栏

const Fiels int = 1
const Directory int = 2
const FielsAndDirectory int = 3

func GetFileByType(path string, fileType int) []os.FileInfo {
	files, _ := ioutil.ReadDir(path)
	var list []os.FileInfo
	for _, f := range files {
		if UnShowFile(f.Name()) { // 隐藏文件跳过
			continue
		}
		if fileType == 1 && !f.IsDir() {
			list = append(list, f)
		}
		if fileType == 2 && f.IsDir() {
			list = append(list, f)
		}
		if fileType == 3 {
			list = append(list, f)
		}
	}
	return list
}

/**
 * 文件或者文件夹前面的包含点不显示
 */
func UnShowFile(name string) bool {
	if name[:1] == "." {
		return true
	} else {
		return false
	}
}

func GetMdTitle(fn string) string {
	c, err := ioutil.ReadFile(fn)
	if err != nil {
		fmt.Errorf("[读取文件错误]:" + err.Error())
	}
	con := string(c)
	// 1 获取第一个h1标签
	h1Con := getTagCon(con)
	return h1Con
}

//删除文件
func RemoveFile(path string) error {
	path = Replace(path, notePath, outPath)
	_err := os.Remove(path)
	return _err
}

//删除文件夹
func RemoveDir(path string) error {
	path = Replace(path, notePath, outPath)
	_err := os.RemoveAll(path)
	return _err
}

// 重命名文件夹
func Rename(path string) error {
	path = Replace(path, notePath, outPath)
	err := os.Rename(path, `重命名文件夹`)
	return err
}

//判断文件夹是否存在
func HasDir(path string) (bool, error) {
	_, _err := os.Stat(path)
	if _err == nil {
		return true, nil
	}
	if os.IsNotExist(_err) {
		return false, nil
	}
	return false, _err
}

//创建文件夹
func CreateDir(path string) {

	_exist, _err := HasDir(path)
	if _err != nil {
		fmt.Printf("获取文件夹异常 -> %v\n", _err)
		return
	}
	if _exist {
		// log("[S]文件夹已存在！")
	} else {
		err := os.Mkdir(path, os.ModePerm)

		if err != nil {
			fmt.Printf("创建目录异常 -> %v\n", err)
		} else {
			// log("[创建成功!]")
		}
	}
}

/**
 * 将地址栏中输出地址转化成 笔记根目录地址
 */
func RootPath(filepath string) string {
	filepath = strings.Replace(filepath, "\\", "/", -1)
	filepath = strings.Replace(filepath, outPath, "", 1)
	filepath = strings.Replace(filepath, notePath, "", 1)
	return filepath
}

func TransName(filename string) string {
	// filename = strings.ToLower(filename)
	filename = strings.Replace(filename, ".md", ".html", 1)
	filename = strings.Replace(filename, "readme", "index", 1)
	filename = strings.Replace(filename, "README", "index", 1)
	return filename
}

func WriteStaticFile(fn string) {
	content, _ := ioutil.ReadFile(fn)
	outFile := Replace(fn, notePath, outPath)

	err := ioutil.WriteFile(outFile, content, 0666) //写入文件(字节数组)
	if err != nil {
		fmt.Errorf("[生成网站文件错误]" + err.Error())
	}
}
